/* eslint-disable no-param-reassign */
/* eslint-disable no-plusplus */

import {
  isEmptyFilterToken,
  isSearchTermToken,
  findFilterItemByName
} from './util'

function onIntent(e) {
  var i
  var item
  var that = e.data.this
  var $target = $(e.target)
  var classes = ['.filtered-search-box']

  that.logger.log('onIntent()')
  // 如果点击的是组件内的元素，则保持激活状态
  for (i = 0; i < classes.length; ++i) {
    if ($target.parents(classes[i]).length > 0) {
      that.lockShow()
      that.focus()
      return
    }
  }
  if (!that.target) {
    return
  }
  that.active = false
  // 如果输入框后面没有筛选器，就不移动输入框了
  if (that.$inputDropdown.next('.js-visual-token').length < 1) {
    return
  }
  item = findFilterItemByName(that.target, that.targetValue)
  if (item) {
    that.selectFilterValue(item.value)
  }
  that.$input.val('')
  that.clearTargetFilter()
  that.resetInputPosition()
}

// 初始化筛选器的事件处理
function initTokenEventHandler(that) {
  that.$el.on('click', '.js-visual-token', function (e) {
    var $value
    var $target = $(e.target)
    var $token = $target.parents('.js-visual-token')

    e.stopPropagation()
    // 如果点击的是删除按钮
    if ($target.hasClass('remove-token')
    || $target.parent().hasClass('remove-token')) {
      $value = $target.parents('.value-container').find('.value')
      that.removeFilterValue($token, $value.data('value'))
      // 如果当前输入框已经获得焦点，则让它保持焦点
      if (that.hasFocus()) {
        that.focus()
        that.deferFocusTime()
      }
      return
    }
    that.editToken($token)
  })
}

// 初始化输入框内的输入事件捕获，用于处理用户手动输入的筛选条件
function initInputTokenCatch(that) {
  var keyHandlers = {
    'Backspace': function (value) {
      var $token

      // 只在输入框内容为空时处理条件删除操作
      if (value) {
        return
      }
      if (that.target) {
        $token = that.$target
        // 如果该筛选标记元素没有值，则切换编辑筛选器名称
        if (isEmptyFilterToken($token)) {
          value = that.target.name
          that.clearTargetFilter()
          that.removeFilterToken($token)
        } else {
          that.popCurrentFilterValue()
          that.buildInputDropdown()
        }
        return
      }
      // 取上一个筛选器，然后删除它的最后一个选项
      $token = that.$inputDropdown.prev('.js-visual-token')
      if ($token.length > 0) {
        if (isSearchTermToken($token)) {
          that.editTerm()
          return
        }
        that.popFilterValue($token)
        if (isEmptyFilterToken($token)) {
          $token.remove()
        }
        that.buildInputDropdown()
      }
    },
    'Enter': function () {
      if (!that.target) {
        that.submit()
        that.buildInputDropdown()
        setTimeout(function () {
          that.$input.focus()
        }, 10)
      }
    },
    ':': function (value) {
      var filter

      if (that.target) {
        that.$input.val(value)
        return
      }
      filter = that.getFilterByName(value)
      if (filter && that.newFilter(filter.key)) {
        that.$input.val('')
        return
      }
      that.$input.val(value)
    },
    // 筛选选项分割符，针对可多选的筛选器
    ',': function (value) {
      var item

      if (!that.target) {
        return
      }
      item = findFilterItemByName(that.target, value)
      if (item && that.selectFilterValue(item.value)) {
        that.$input.val('')
        that.input = ''
        that.buildFilterDropdown(that.target)
      } else {
        that.$input.val(value)
      }
    },
    // 筛选结束符
    ';': function (value) {
      var item

      if (!that.target) {
        that.$input.val(value)
        return
      }
      item = findFilterItemByName(that.target, value)
      if (item && that.selectFilterValue(item.value)) {
        that.$input.val('')
        that.input = ''
        that.clearTargetFilter()
      } else {
        that.$input.val(value)
      }
    }
  }

  that.$input.on({
    focus: function () {
      that.$el.addClass('focus')
    },
    blur: function () {
      that.$el.removeClass('focus')/**
      that.active = false
      that.deferFocusTime() */
    },
    input: function () {
      that.input = that.$input.val()
      that.updateState()
      if (that.target && that.target.searchOption) {
        const key = that.target.key
        if (that.target.timeOutId) {
          clearTimeout(that.target.timeOutId)
        }
        that.target.timeOutId = setTimeout(() => {
          if (that.input.length) {
              if (!that.target || !that.target.searchOption) return
              that.target.searchOption.fetcher(that.input, (data) => {
                if (key === that.target.key) {
                  that.target.items = that.target.items.filter(item => item.key !== that.target.searchOption.key)
                  const items = that.target.searchOption.converter(data)
                  that.target.items = that.target.items.concat(items)
                  that.buildRemoteSearchDropdownItems(that.target.searchOption.key, items)
                }
                that.setTabSelected()
              })
          } else {
            that.buildRemoteSearchDropdownItems(that.target.searchOption.key, [])
            if (that.$inputDropdownMenu.find('.item').not('.filtered').length) {
              that.buildSearchTip(that.target.searchOption.searchTip)
            }
            that.$el.find(`.tab[data-tab=${that.target.tabs[0].key}]`).trigger('click')
          }
        }, 400)
      }
    }
  })
  that.$el.on('click', function () {
    that.focus()
  })
  that.$input.on('keydown', function (e) {
    var val = that.$input.val()

    if (!keyHandlers[e.key]) {
      return
    }
    // 延迟一会，避免在给输入框赋值后又被后面的 inout 事件重置
    setTimeout(function () {
      keyHandlers[e.key](val)
    }, 10)
  })
}

function initTabEventHandler(target) {
  target.$el.on('click', '.tab', function (e) {
    target.$inputDropdownMenu.find('.tab').removeClass('active')
    $(e.target).addClass('active')
    target.$inputDropdownMenu.find('.item').addClass('hide')
    target.$inputDropdownMenu.find(`.item[data-tab=${$(e.target).data('tab')}]`).removeClass('hide')
  })
}

// 初始化“清除”按钮
function initClearButton(that) {
  that.$btnClearSearch.on('click', function () {
    that.clear()
    that.commit()
  })
}

export function bindIntent(target) {
  $(document).on('mousedown', { this: target }, onIntent)
}

export function unbindIntent() {
  $(document).off('mousedown', onIntent)
}

// 阻止已冒泡到 document 的 click 事件的处理
export function stopIntent(that) {
  unbindIntent()
  setTimeout(function () {
    bindIntent(that)
  }, 100)
}

export function bindEventHandlers(target) {
  initTokenEventHandler(target)
  initInputTokenCatch(target)
  initClearButton(target)
  initTabEventHandler(target)
}

export function unbindEventHandlers() {
  unbindIntent()
}
